home *** CD-ROM | disk | FTP | other *** search
- Path: info.uah.edu!oreo!gbacon
- From: gbacon@oreo (Greg Bacon)
- Newsgroups: comp.lang.c
- Subject: Re: union ?
- Date: 18 Jan 1996 20:20:52 GMT
- Organization: The University of Alabama in Huntsville
- Message-ID: <4dma34$bsi@info.uah.edu>
- References: <4dkigi$c29@linet02.li.net>
- Reply-To: gbacon@CS.UAH.Edu
- NNTP-Posting-Host: oreo.aspire.cs.uah.edu
- X-Newsreader: TIN [version 1.2 PL2]
-
- Don Matthews (don@newshost.li.net) wrote:
- : A union consist of many different variables.
- : But at any one time it can only hold one of those variables.
- : Is that correct?
-
- Errr... not exactly. You see, given any chunk of memory (which will
- consist of just 1's and 0's), the computer doesn't know if it's
- character data, integer data, or float data; it's all in how the
- programmer interprets it.
-
- A union is identical to a structure with the exception that all the
- offsets are zero. So while you can send data into the union as one
- type, you can get it out as another. For example, a common way
- of getting around the byte-order problem for your data files looks
- something like this.
-
- {
- union
- {
- char c[4];
- int i;
- } u;
-
- copy_string_data(string, u.c);
-
- write_to_file(htonl(u.i));
-
- Of course, string is some (likely) character string outside this
- scope and the copy_string_data() function just puts 4 chars into
- the array it gets a pointer to. htonl() you find on UNIX platforms.
- It converts its argument from host to network byte order. Voila!
- Instant portable data files.
-
- So, you see, there isn't "room" enough in the same union for 4 chars
- _and_ an int, it's just an easy way of interpreting the same data
- in multiple ways.
-
- Hope this helps,
- Greg
- --
- Greg Bacon <gbacon@cs.uah.edu>
- University of Alabama in Huntsville
- CS Department Systems Support Team
-